package com.simple.json.clazz.basic;

import java.lang.reflect.Field;

import org.json.JSONObject;

import com.simple.json.Util;
import com.simple.json.clazz.ClassInterface;

public class DoubleClass implements ClassInterface {

	private DoubleClass() {
	}

	private final static DoubleClass instance = new DoubleClass();

	public static DoubleClass getInstance() {
		return instance;
	}

	private Double getValue(Object value) {
		// 强转为字符串，这样就可以调用valueOf方法了。
		String strValue = value + "";
		try {
			return Double.valueOf(strValue);
		} catch (Exception e) {
			Util.logerr( strValue + " can not be casted as Double, return value 0");
			return Double.valueOf(0);
		}
	}

	@Override
	public Class<?> getProcessClassType() {
		return Double.class;
	}

	@Override
	public <T> boolean setRightValueToField(T targetObject, Field targetField,
			JSONObject jsonObject) {
		Class<?> fieldClass = targetField.getType();
		if (!fieldClass.getName().equals(getProcessClassType().getName())) {
			return false;
		}

		try {
			Object value = jsonObject.opt(targetField.getName());
//			targetField.setAccessible(true);
			Double doubleValue = getValue(value);
			targetField.set(targetObject, doubleValue);
			Util.logout("set " + targetField.getName() + "'s Double value = " + doubleValue);
			return true;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Object getRightValue(Object value) {
		return getValue(value);
	}

}
